const base = require("./../../base");
const moment = require("moment");
const got = require("got");

module.exports = class extends base {
    async _initialize() {
        await super.isCustomAuth();
        await super.isAppAuth();
        await super.isShopAuth();
    }

    async _before_serviceUp() {
        await super.isWxaAuth();
    }

    async _before_update() {
        await super.isWxaAuth();
    }
    /**
     *
     * @api {get} /shop/home/shop/order/index/index 订单列表
     * @apiDescription 订单列表
     * @apiGroup Shop/Home
     * @apiVersion 0.0.1
     *
     * @apiHeader {String} Token 用户授权token.
     * @apiHeader {String} AppToken 应用授权token.
     *
     * @apiParam {Number} type       关键
     * @apiParam {Number} keyWord    关键词
     * @apiParam {Number} pay_status 支付状态
     * @apiParam {Number} status     状态
     * @apiParam {Number} start_time 开始时间
     * @apiParam {Number} end_time   结束时间
     * @apiParam {Number} page       页码
     *
     * @apiSampleRequest /shop/home/shop/order/index/index
     *
     */

    async index() {
        const shopId = this.state.shop.id;
        const {
            page = 1,
            status,
            type = "orderid",
            keyWord,
            pay_status,
            start_time,
            end_time
        } = this.query;
        const res = await this.model("order")
            .query(qb => {
                qb.where("shop_id", shopId);
                if (this.isSet(status)) {
                    qb.where("status", status);
                }
                if (this.isSet(type) && this.isSet(keyWord)) {
                    qb.where(type, "like", "%" + keyWord + "%");
                }
                if (this.isSet(pay_status)) {
                    qb.where("pay_status", pay_status);
                }
                if (this.isSet(start_time) && !this.isSet(end_time)) {
                    qb.where("created_at", ">", start_time);
                }
                if (!this.isSet(start_time) && this.isSet(end_time)) {
                    qb.where("created_at", "<", end_time);
                }
                if (this.isSet(start_time) && this.isSet(end_time)) {
                    qb.where("created_at", ">", start_time);
                    qb.where("created_at", "<", end_time);
                }
                qb.orderBy("id", "desc");
            })
            .fetchPage({
                pageSize: 20,
                page: page,
                withRelated: [
                    "detail.product",
                    "contact",
                    "verify",
                    "kuaidi",
                    "store"
                ]
            });
        this.success(res);
    }

    /**
     *
     * @api {get} /shop/home/shop/order/index/detail 订单详情
     * @apiDescription 订单详情
     * @apiGroup Shop/Home
     * @apiVersion 0.0.1
     *
     * @apiHeader {String} Token 用户授权token.
     * @apiHeader {String} AppToken 应用授权token.
     *
     * @apiParam {Number} id  订单id
     *
     * @apiSampleRequest /shop/home/shop/order/index/detail
     *
     */
    async detail() {
        const shopId = this.state.shop.id;
        const { id } = this.query;
        if (!this.isSet(id)) {
            this.error("没有数据");
            return;
        }
        const res = await this.model("order")
            .query(qb => {
                qb.where("shop_id", shopId);
                qb.where("id", id);
            })
            .fetch({
                withRelated: [
                    "detail.product",
                    "contact",
                    "user",
                    "service",
                    "verify",
                    "kuaidi",
                    "store"
                ]
            });

        this.success(res);
    }

    /**
     *
     * @api {get} /shop/home/shop/order/index/update 修改订单状态
     * @apiDescription 修改订单状态
     * @apiGroup Shop/Home
     * @apiVersion 0.0.1
     *
     * @apiHeader {String} Token 用户授权token.
     * @apiHeader {String} AppToken 应用授权token.
     * @apiHeader {String} WxaToken 小程序授权token.
     *
     * @apiParam {Number} id           订单id
     * @apiParam {Number} status       0:待发货，1:已发货，2:已完成，3:已评价,4退款完成，5售后完成, -1:已关闭，-2:退款中，-3售后
     * @apiParam {Number} delivery_id  快递id
     * @apiParam {String} code         快递单号
     *
     * @apiSampleRequest /shop/home/shop/order/index/update
     *
     */
    async update() {
        const shopId = this.state.shop.id;
        // const authorizer_appid = this.state.wxa.authorizer_appid;
        const data = this.query;
        if (!this.isSet(data.id) || !this.isSet(data.status)) {
            this.error("没有数据");
            return;
        }
        const order = await this.model("order")
            .query(qb => {
                qb.where("shop_id", shopId);
                qb.where("id", data.id);
            })
            .fetch();
        // if (Number(data.status) === 4 && Number(order.status) === -2) {
        //     if (Number(order.payment_id) === 1 && Number(order.check) === 3) {
        //         // 从trade表中进行退款
        //         const trade_info = await this.model("trade")
        //             .query(qb => {
        //                 qb.where("id", order.trade_id);
        //                 qb.where("status", 1);
        //             })
        //             .fetch();
        //         if (trade_info.id) {
        //             const url =
        //                 process.env.APP_HOST +
        //                 `/pay/wxpay/refund?id=${trade_info.id}`;
        //             const list = await got.get(url, {
        //                 headers: {
        //                     Referer: `https://servicewechat.com/${authorizer_appid}/devtools/page-frame.html`
        //                 }
        //             });
        //         }
        //     }
        // }
        if (Number(data.status) === 1) {
            if (Number(order.status) !== 0 || Number(order.check) > 1) {
                this.fail(`订单${order.orderid}不满足发货条件`);
                return;
            }
            order.send_time = moment().format("YYYY-MM-DD HH:mm:ss");
            const delivery = await this.model("shop_kuaidi")
                .query(qb => {
                    qb.where("id", data.delivery_id);
                    qb.where("status", 1);
                })
                .fetch();
            if (delivery.id) {
                await this.model("order_kuaidi")
                    .forge({
                        order_id: data.id,
                        shop_id: delivery.shop_id,
                        delivery_id: delivery.id,
                        delivery_name: delivery.delivery_name,
                        delivery_code: delivery.delivery_code,
                        tracking_number: data.code
                    })
                    .save();
            }
        }

        const saveData = {
            id: data.id,
            status: data.status,
            send_time: order.send_time
        };
        if (Number(data.status) === 2) {
            saveData["finsh_time"] = moment().format("YYYY-MM-DD HH:mm:ss");
        }

        const res = await this.model("order")
            .forge(saveData)
            .save();
        this.success(res);
    }

    /**
     *
     * @api {get} /shop/home/shop/order/index/service 售后列表
     * @apiDescription 售后列表
     * @apiGroup Shop/Home
     * @apiVersion 0.0.1
     *
     * @apiHeader {String} Token 用户授权token.
     * @apiHeader {String} AppToken 应用授权token.
     *
     * @apiParam {Number} page 页码
     *
     * @apiSampleRequest /shop/home/shop/order/index/service
     *
     */
    async service() {
        const shopId = this.state.shop.id;
        const { page = 1 } = this.query;
        const res = await this.model("order_service")
            .query(qb => {
                qb.where("shop_id", shopId);
            })
            .fetchPage({
                pageSize: 20,
                page: page,
                withRelated: ["order", "service"]
            });
        this.success(res);
    }

    /**
     *
     * @api {get} /shop/home/shop/order/index/serviceUp 通过/拒绝
     * @apiDescription 通过/拒绝
     * @apiGroup Shop/Home
     * @apiVersion 0.0.1
     *
     * @apiHeader {String} Token 用户授权token.
     * @apiHeader {String} AppToken 应用授权token.
     * @apiHeader {String} WxaToken 小程序授权token.
     *
     * @apiParam {Number} id       售后id
     * @apiParam {Number} status   状态 -1：拒绝 1：通过
     *
     * @apiSampleRequest /shop/home/shop/order/index/serviceUp
     *
     */
    async serviceUp() {
        const shopId = this.state.shop.id;
        const authorizer_appid = this.state.wxa.authorizer_appid;
        const { id, status, refuse = "" } = this.query;
        const service = await this.model("order_service")
            .query(qb => {
                qb.where("id", id);
            })
            .fetch();

        const order = await this.model("order")
            .query(qb => {
                qb.where("id", service.order_id);
                if (Number(service.type) === 1) {
                    qb.where("check", 3);
                }
                if (Number(service.type) === 0) {
                    qb.where("check", 2);
                }
            })
            .fetch();

        if (!order) {
            this.fail("参数错误");
            return;
        }
        if (Number(status) === 1) {
            if (Number(service.type) === 1) {
                if (
                    Number(order.payment_id) === 1 &&
                    Number(order.pay_status) === 1 &&
                    Number(order.check) === 3
                ) {
                    // 从trade表中进行退款
                    const trade_info = await this.model("trade")
                        .query(qb => {
                            qb.where("id", order.trade_id);
                            qb.where("status", 1);
                        })
                        .fetch();
                    if (trade_info) {
                        const url =
                            process.env.APP_HOST +
                            `/app/pay/wxpay/refund?id=${trade_info.id}`;
                        const list = await got.get(url, {
                            headers: {
                                AppToken:
                                    this.query.AppToken || this.get("AppToken")
                            }
                        });
                        order.status = 4;
                    } else {
                        this.fail("订单参数错误");
                        return;
                    }
                }
            } else {
                order.status = 5;
            }
        }

        await this.model("order")
            .forge({ id: order.id, check: status, status: order.status })
            .save();
        const res = await this.model("order_service")
            .forge({ id: id, status: status, refuse: refuse })
            .save();
        this.success(res);
    }

    /**
     *
     * @api {get} /shop/home/shop/order/index/delivery 一键发货
     * @apiDescription 一键发货
     * @apiGroup Shop/Home
     * @apiVersion 0.0.1
     *
     * @apiHeader {String} Token 用户授权token.
     * @apiHeader {String} AppToken 应用授权token.
     * @apiHeader {String} WxaToken 小程序授权token.
     *
     * @apiParam {String} id       订单ids
     *
     * @apiSampleRequest /shop/home/shop/order/index/delivery
     *
     */
    async delivery() {
        const shopId = this.state.shop.id;
        const { id } = this.query;
        const ids = id ? id.split(",") : [];
        if (!ids.length) {
            this.fail("参数错误");
            return;
        }
        const order = await this.model("order")
            .query(qb => {
                qb.whereIn("id", ids);
            })
            .fetchAll();
        const arr = [];
        for (let i = 0; i < order.length; i++) {
            if (Number(order[i].status) !== 0 || Number(order[i].check) > 1) {
                this.fail(`订单${order[i].orderid}不满足发货条件`);
                return;
            }

            if (
                Number(order[i].payment_id) !== 3 &&
                Number(order[i].pay_status) !== 1
            ) {
                this.fail(`订单${order[i].orderid}不满足发货条件`);
                return;
            }
            const send_time = moment().format("YYYY-MM-DD HH:mm:ss");
            const obj = {
                id: order[i].id,
                send_time: send_time,
                status: 1
            };
            arr.push(obj);
        }

        const res = await doodoo.bookshelf.Collection.extend({
            model: this.model("order")
        })
            .forge(arr)
            .invokeThen("save");
        this.success(res);
    }
};
